package optimizers.tools;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Random;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import optimizers.commons.GAConstants;
import optimizers.commons.GAIndiv;


import parallelism.SystemFindingTask;
import parallelism.SystemResult;

public class BistableGenerator {

	
	public static void generateInits(int NoOfSimpleSeq, int PopSize, String filename){
		GAIndiv[] curGen = new GAIndiv[PopSize];
		ExecutorService eservice;
		CompletionService<Object> cservice;
		eservice = Executors.newFixedThreadPool(GAConstants.nMathLink);
		cservice = new ExecutorCompletionService<Object>(
		eservice);
		int taskCount = 0;

		for (int i = 0; i < PopSize; i++) {
			cservice.submit(new SystemFindingTask(NoOfSimpleSeq,
					new Random(), i));
			taskCount++;
		}

		for (int i = 0; i < taskCount; i++) {
			try {
				SystemResult result = (SystemResult) cservice
						.take().get();
				curGen[result.index] = result.indiv;
				System.out.println(i + ": Indiv " + result.index+ " created");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		FileOutputStream saveFile;
		try {
			saveFile = new FileOutputStream(filename);
			ObjectOutputStream save = new ObjectOutputStream(saveFile);
			save.writeObject(curGen);
			save.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		BistableGenerator.generateInits(4, 2, "Test.dat");
	}
}
